<?php
class AdminGenerator {
    private $host = "";
    private $user = "";
    private $password = "";
    private $databaseName = "";
    
    function __construct($host,$user,$password,$databaseName) {
        $this->host = $host;
        $this->user = $user;
        $this->password = $password;
        $this->databaseName = $databaseName;
        mysql_connect($host, $user, $password);
        mysql_select_db($databaseName);
    }
    function createDatabaseModel() {
        // create database model
        $file = new FileManager('Model/DatabaseModel.php');
        $data = '<?php
    abstract class DatabaseModel {
    protected function setDatabaseConnection() {
        mysql_connect("'.$this->host.'", "'.$this->user.'", "'.$this->password.'");
        mysql_select_db("'.$this->databaseName.'");
    }
    abstract function insertTransaction();
    abstract function updateTransaction();
    abstract function deleteTransaction();
    abstract function getData($filter);
}
?>';
        $fw = $file->getContentFileToWrite();
        $file->writeFile($fw, $data);
        echo "Database model created <br>";
    }
    function createController() {
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $resultFieldTabel = mysql_query("desc $tableName");
            $file = new FileManager('Controller/Controller'.$tableName.'.php');
            $fw = $file->getContentFileToWrite();
            $dataFile = '<?php
/**
 * Description of Controller'.$tableName.'
 *
 * @author Mirza
 */
class Controller'.$tableName.' {
';
            $keyField = '';
            $atribut = '';
            $insertQuery = 'public static function insert'.$tableName.'(';
            $updateQuery = 'public static function update'.$tableName.'(';
            $deleteQuery = 'public static function delete'.$tableName.'(';
            $searchQuery = 'public static function search'.$tableName.'($filter){
        $model'.$tableName.' = new Model'.$tableName.'();
        return $model'.$tableName.'->getData($filter);
    }';
            $insertBody = '$model'.$tableName.' = new Model'.$tableName.'();
';
            $updateBody = '$model'.$tableName.' = new Model'.$tableName.'();
';
            $deleteBody = '$model'.$tableName.' = new Model'.$tableName.'();
';

            $n = mysql_num_rows($resultFieldTabel);
            while(($dataTableName = mysql_fetch_array($resultFieldTabel)) != null) {
                $fieldName = $dataTableName['Field'];                
                $updateBody = $updateBody . '$model'.$tableName.'->'.$fieldName.' = $'.$fieldName.';
';
                if ($n == 1) {
                    $updateQuery = $updateQuery . '$'.$fieldName.'';
                    if ($dataTableName['Key'] != 'PRI') {
                        $insertQuery = $insertQuery . '$'.$fieldName.'';
                        $insertBody = $insertBody . '$model'.$tableName.'->'.$fieldName.' = $'.$fieldName.';
';
                    } else {
                        $deleteQuery = $deleteQuery . '$'.$fieldName.'';
                        $deleteBody = $deleteBody . '$model'.$tableName.'->'.$fieldName.' = $'.$fieldName.';
';
                    }
                } else {
                    $updateQuery = $updateQuery . '$'.$fieldName.',';
                    if ($dataTableName['Key'] != 'PRI') {
                        $insertQuery = $insertQuery . '$'.$fieldName.',';
                        $insertBody = $insertBody . '$model'.$tableName.'->'.$fieldName.' = $'.$fieldName.';
';
                    } else {
                        $deleteQuery = $deleteQuery . '$'.$fieldName.'';
                        $deleteBody = $deleteBody . '$model'.$tableName.'->'.$fieldName.' = $'.$fieldName.';';
                    }
                }
                $n--;
            }
            $insertQuery = $insertQuery . ') {
'.$insertBody.'$model'.$tableName.'->insertTransaction();
}
';
            $updateQuery = $updateQuery . ') {
'.$updateBody.'$model'.$tableName.'->updateTransaction();
}
';
            $deleteQuery = $deleteQuery . ') {
'.$deleteBody.'$model'.$tableName.'->deleteTransaction();
}
';


            $dataFile = $dataFile . $insertQuery.'
'.$updateQuery. '
'.$deleteQuery.'
'.$searchQuery.'
            }
?>';
            $file->writeFile($fw, $dataFile);
            echo "Controller ".$tableName." Created<br>";
        }
    }
    function createModel() {
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $resultFieldTabel = mysql_query("desc $tableName");
            $file = new FileManager('Model/Model'.$tableName.'.php');
            $fw = $file->getContentFileToWrite();
            $dataFile = '<?php
require_once \'DatabaseModel.php\';
/**
 * Description of Model'.$tableName.'
 *
 * @author Mirza
 */
class Model'.$tableName.' extends DatabaseModel{
function __construct(){
    parent::setDatabaseConnection();
}
';
            $keyField = '';
            $atribut = '';
            $insertQueryHead = 'insert into '.$tableName.'(';
            $insertQueryTail = 'values (';
            $updateQuery = 'update '.$tableName.' set ';
            $deleteQuery = 'delete from '.$tableName.' where ';
            $selectQuery = '    public function getData($filter) {
        $selectQuery = new SelectQuery("'.$tableName.'", $filter);
        return $selectQuery;
    }';
            $n = mysql_num_rows($resultFieldTabel);
            while(($dataTableName = mysql_fetch_array($resultFieldTabel)) != null) {
                $fieldName = $dataTableName['Field'];
                $atribut = $atribut . 'public $'.$fieldName.';
';
                if ($dataTableName['Key'] != 'PRI') {
                    if ($n == 1) {
                        $insertQueryHead = $insertQueryHead . $fieldName;
                        $insertQueryTail = $insertQueryTail . '\'$this->'.$fieldName.'\'';
                        $updateQuery = $updateQuery . $fieldName. ' = \'$this->'.$fieldName.'\'';
                    } else {
                        $insertQueryHead = $insertQueryHead . $fieldName . ',';
                        $insertQueryTail = $insertQueryTail . '\'$this->'.$fieldName.'\',';
                        $updateQuery = $updateQuery . $fieldName. ' = \'$this->'.$fieldName.'\',';
                    }
                }
                if ($dataTableName['Key'] == 'PRI') {
                    $keyField = $dataTableName['Field'];
                }
                $n--;
            }
            $insertQueryHead = $insertQueryHead . ')';
            $insertQueryTail = $insertQueryTail . ')';
            $insertQuery = 'public function insertTransaction() {
DMLQuery::runDMLQuery("'.$insertQueryHead.$insertQueryTail.'");
}';

            $deleteQuery = 'public function deleteTransaction() {
DMLQuery::runDMLQuery("'.$deleteQuery . $keyField . ' = \'$this->'.$keyField.'\'");
}';

            $updateQuery = 'public function updateTransaction() {
DMLQuery::runDMLQuery("'.$updateQuery . ' where '. $keyField . ' = \'$this->'.$keyField.'\'");
}';
            $dataFile = $dataFile . $atribut . $insertQuery. '
'.$deleteQuery. '
'.$updateQuery.'
'.$selectQuery.'
            }
?>';
            $file->writeFile($fw, $dataFile);
            echo "Model ".$tableName." Created<br>";
        }
    }
    function createHeader() {
        $file = new FileManager('Admin/Menu/Header.php');
        $fw = $file->getContentFileToWrite();
        $dataFile = '<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <?php
        require_once "@includer.php";
    ?>
    <script src="Admin/JS/HttpListener.js"></script>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Content Management System</title>
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <link href="Admin/Style/default.css" rel="stylesheet" type="text/css"/>
</head>
<body onload=\'showMenuContent("index.php","")\'>
<!-- start header -->
<div id="header">
    <div id="logo">
        <h1><a href="#">Content Management System</a></h1>
        <h2></h2>
    </div>
    <div id="menu">
        <ul>
            <?php
            if ($_SESSION["userNameAdmin"] != "") {
                ?>';
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $dataFile = $dataFile . '<li><a href="#" onclick="showMenuContent(\'Daftar'.$tableName.'.php\',\'\')">Admin '.$tableName.'</a></li>
';
        }
        $dataFile = $dataFile . '<li><a href="index_admin.php?logout=true">Logout</a></li>
<?php
        }
        ?>
        </ul>
    </div>
</div>';
        $file->writeFile($fw, $dataFile);
        echo "Header File Created<br>";
    }
    function createIncluderMenu() {
        $file = new FileManager('Admin/Menu/@includer.php');
        $fw = $file->getContentFileToWrite();
        $dataFile = '
<script src="Admin/JS/ElementListener.js"></script>
<?php
require_once("Lib/DML Query.php");
require_once("Lib/Select Query.php");
';
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $dataFile = $dataFile . 'require_once("Model/Model'.$tableName.'.php");
';
            $dataFile = $dataFile . 'require_once("Controller/Controller'.$tableName.'.php");
';
        }
        $dataFile = $dataFile . '
require_once("Admin/Page Action/LoginAction.php");
require_once("Admin/Page Action/LogoutAction.php");
?>';
        $file->writeFile($fw, $dataFile);
        echo "@includer menu File Created<br>";
    }
    function createIncluderPageView() {
        $file = new FileManager('Admin/Page View/@includer.php');
        $fw = $file->getContentFileToWrite();
        $dataFile = '
<?php
require_once("../../Lib/DML Query.php");
require_once("../../Lib/Select Query.php");
';
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $dataFile = $dataFile . 'require_once("../../Model/Model'.$tableName.'.php");
';
            $dataFile = $dataFile . 'require_once("../../Controller/Controller'.$tableName.'.php");
';
        }
        $dataFile = $dataFile . '?>';
        $file->writeFile($fw, $dataFile);
        echo "@includer page view Created<br>";
    }
    function createDaftarView() {
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $file = new FileManager('Admin/Page View/Daftar'.$tableName.'.php');
            $fw = $file->getContentFileToWrite();
            $resultFieldTabel = mysql_query("desc $tableName");
            $n = mysql_num_rows($resultFieldTabel);
            $i = 1;

            $keyField = '';
            $requestUpdate = '';
            $requestInsert = '';
            $judulTabel = '';
            $dataTabel = '';
            $dataTabel2 = '';
            while(($dataTableName = mysql_fetch_array($resultFieldTabel)) != null) {
                if ($n == 1) {
                    $requestUpdate = $requestUpdate . '$_REQUEST["el'.$i.'"]';
                    $requestInsert = $requestInsert . '$_REQUEST["el'.($i-1).'"]';
                } else {
                    $requestUpdate = $requestUpdate . '$_REQUEST["el'.$i.'"],';
                    if ($i > 1)
                    $requestInsert = $requestInsert . '$_REQUEST["el'.($i-1).'"],';
                }
                if ($dataTableName['Key'] == 'PRI') {
                    $keyField = $dataTableName['Field'];
                } else {
                    $dataTabel = $dataTabel . '<td class = \'td1\'>".substr($data[\''.$dataTableName['Field'].'\'],0,50)."</td>';
                    $dataTabel2 = $dataTabel2 . '<td class = \'td2\'>".substr($data[\''.$dataTableName['Field'].'\'],0,50)."</td>';
                    if ($n == 1) {
                        $judulTabel = $judulTabel . '<th colspan=3>'.$dataTableName['Field'].'</th>';
                    }
                    else {
                        $judulTabel = $judulTabel . '<th>'.$dataTableName['Field'].'</th>';
                    }
                }
                $i++;
                $n--;
            }
            $judulTabel = str_replace('_', ' ', $judulTabel);
            $dataField = '<?php
require_once "@includer.php";
if ($_REQUEST["action"] == "update") {
    Controller'.$tableName.'::update'.$tableName.'('.$requestUpdate.');
    echo "Data berhasil diubah <br><br>";
} else if ($_REQUEST["action"] == "insert") {
    Controller'.$tableName.'::insert'.$tableName.'('.$requestInsert.');
    echo "Data berhasil ditambah <br><br>";
}  else if ($_REQUEST["action"] == "delete") {
    Controller'.$tableName.'::delete'.$tableName.'($_REQUEST["'.$keyField.'"]);
    echo "Data berhasil dihapus <br><br>";
}
$result = Controller'.$tableName.'::search'.$tableName.'("");
?>

<a href=\'#\' onclick="showMenuContent(\'Form'.$tableName.'.php\',\'&action=insert\')"><img src="Admin/Style/images/add.png" width="20" height="20"></a><br><br>
<?php
echo "<table><tr>'.$judulTabel.'</tr>";
$i = 0;
while(($data = $result->getRecordStringParameter()) != null) {
    if($i % 2 == 0)
        echo "<tr>'.$dataTabel.'";
    else
        echo "<tr>'.$dataTabel2.'";
    if($i % 2 == 0){
    ?>
    <td class=\'editField1\'><a href=\'#\' onclick="showMenuContent(\'Form'.$tableName.'.php\',\'&action=update&'.$keyField.'=<?php echo $data[\''.$keyField.'\'];?>\')"><img src="Admin/Style/images/check.png" width="20" height="20"></a></td>
    <td class=\'editField1\'><a href=\'#\' onclick="showMenuContent(\'Daftar'.$tableName.'.php\',\'&action=delete&'.$keyField.'=<?php echo $data[\''.$keyField.'\'];?>\')"><img src="Admin/Style/images/delete.png" width="20" height="20"></a></td></tr>
<?php
    } else {
    ?>
    <td class=\'editField2\'><a href=\'#\' onclick="showMenuContent(\'Form'.$tableName.'.php\',\'&action=update&'.$keyField.'=<?php echo $data[\''.$keyField.'\'];?>\')"><img src="Admin/Style/images/check.png" width="20" height="20"></a></td>
    <td class=\'editField2\'><a href=\'#\' onclick="showMenuContent(\'Daftar'.$tableName.'.php\',\'&action=delete&'.$keyField.'=<?php echo $data[\''.$keyField.'\'];?>\')"><img src="Admin/Style/images/delete.png" width="20" height="20"></a></td></tr>
    <?php
    }
$i++;
}
?>';
            $file->writeFile($fw, $dataField);
        }
        echo "Daftar View Created";
    }
    function createFormView() {
        $result = mysql_query("show table status from $this->databaseName");
        while(($data = mysql_fetch_array($result)) != null) {
            $tableName = $data["Name"];
            $file = new FileManager('Admin/Page View/Form'.$tableName.'.php');
            $fw = $file->getContentFileToWrite();
            $resultFieldTabel = mysql_query("desc $tableName");
            $n = mysql_num_rows($resultFieldTabel);
            $i = 1;
            $keyField = '';
            $ubahForm = '';
            $masukkanForm = '';
            while(($dataTableName = mysql_fetch_array($resultFieldTabel)) != null) {
                if ($dataTableName['Key'] == 'PRI') {
                    $keyField = $dataTableName['Field'];
                } else {
                    if ($dataTableName['Type'] == 'text') {
                        $ubahForm = $ubahForm . '<tr><td class=\'colomnLabel\'>'.str_replace('_', ' ', $dataTableName['Field']).'</td><td><textarea id="el'.($i).'" cols=120 rows=9><?php echo $data[\''.$dataTableName['Field'].'\'];?></textarea></td></tr>
';
                        $masukkanForm = $masukkanForm . '<tr><td class=\'colomnLabel\'>'.str_replace('_', ' ', $dataTableName['Field']).'</td><td><textarea id="el'.($i - 1).'" cols=120 rows=9></textarea></td></tr>
';
                    } else {
                        $ubahForm = $ubahForm . '<tr><td class=\'colomnLabel\'>'.str_replace('_', ' ', $dataTableName['Field']).'</td><td><input size = 80 type="text" id="el'.($i).'" value="<?php echo $data[\''.$dataTableName['Field'].'\'];?>"></td></tr>
';
                        $masukkanForm = $masukkanForm . '<tr><td class=\'colomnLabel\'>'.str_replace('_', ' ', $dataTableName['Field']).'</td><td><input type="text" id="el'.($i-1).'" value="" size = 80></td></tr>
';
                    }
                }
                $i++;
                $n--;
            }
            $judulTabel = str_replace('_', ' ', $judulTabel);
            $dataField = '<?php
require_once \'@includer.php\';
if ($_REQUEST[\'action\'] == \'update\') {
    $'.$keyField.' = $_REQUEST[\''.$keyField.'\'];
    $result = Controller'.$tableName.'::search'.$tableName.'("where '.$keyField.' = $'.$keyField.'");
    $data = $result->getRecordStringParameter();
?>
<input type="hidden" id="el1" value="<?php echo $data[\''.$keyField.'\'];?>">
<table>    
    '.$ubahForm.'
    <tr><td></td><td><button onclick="sendElement(\'update\','.($i - 1).',\'Daftar'.$tableName.'.php\')">Ubah</button><button onclick="showMenuContent(\'Daftar'.$tableName.'.php\',\'\')">Batal</button></td></tr>
    </table>
<?php
} else if ($_REQUEST[\'action\'] == \'insert\') {
?>
    <table>
    '.$masukkanForm.'
    <tr><td></td><td><button onclick="sendElement(\'insert\','.($i - 2).',\'Daftar'.$tableName.'.php\')">Simpan</button><button onclick="showMenuContent(\'Daftar'.$tableName.'.php\',\'\')">Batal</button></td></tr>
    </table>
<?php
}
?>';
            $file->writeFile($fw, $dataField);
        }
        echo "<br>Form View Created";
    }
}
?>
